package thread.synchroCode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class SxfPrintString {
  public static void main(String[] args) throws InterruptedException {
    List<String> strings = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
      strings.add(String.valueOf(i));
    }

    PrintClass printClass = new PrintClass(strings, 0);

    CountDownLatch countDownLatch = new CountDownLatch(5);

    for (int i = 0; i < 5; i++) {
      new Thread(() -> {
        while (printClass.print()){

        }
        countDownLatch.countDown();
      }).start();
    }

    countDownLatch.await();
  }
  /**
   *  请用2个（或者n个）线程竞争去取出list中的string打印
   *         // 每个list中的string只能被1个而不是多个线程打印
   *         // 每个线程都是从索引0开始到list中取string， 如果要取的索引被别的索引获取了就不能获取
   */

  public static class PrintClass {
    private List<String> strs;
    private int index;

    private HashMap map;

    public PrintClass(List<String> strs, int index) {
      this.strs = strs;
      this.index = index;
    }

    public synchronized boolean print(){
      if (strs.size() <= index){
        return false;
      }
      String currPrintText = strs.get(index);
      System.out.println(Thread.currentThread().getName() + ':' + currPrintText);
      index++;
      return true;
    }
  }
}
